import time
from fileinput import filename
import pymysql

# 3.开发python脚本，每隔2秒读取日志文件
# a)使用open + while +  time + pymysql模块将数据读取出来
# b)并分析里面的5种日志级别，将出现的次数实施写到数据库。但是F和E的日志需要将详情写到数据库中。

user = "root"
pwd = "root"
addr = "localhost"
database = "app_log"
db = pymysql.connect(host=addr, user=user, password=pwd, db=database)
cursor = db.cursor()
sql = "INSERT INTO log_info (create_time, log_level, log_count, log_detail) VALUES (%s, %s, %s, %s);"
def insertbd(sql,prom):
    cursor.execute(sql, prom)
    db.commit()

i = 0
count = 0
while 1:
    i += 1
    if i >10:
        break
    # # 打开文件并读取内容
    # with open("F:/DTGK/log/a.log", 'r', encoding='utf-8') as file:
    #     content = file.read()
    #     print(content)
    # time.sleep(2)
    log = open("F:/DTGK/log/a.log", 'r', encoding='utf-8')
    lines = log.readlines()
    for line in lines[1:]:
        lo = []
        data = line.split(',')
        for j in data:
            count += 1
            log_va = j.split(' ')
            if len(log_va) >6 and log_va[6] in "FEWID":
                lo.append("2024-" + log_va[0]+" "+log_va[1][:8])
                lo.append(log_va[6])
                lo.append(count)
                lo.append(j[40:])
                insertbd(sql,lo)
                print(lo)
            # print(j)
            # print(log_va[0]+" "+log_va[1][:8]) #时间
            # print(log_va[6]) #等级
            #print(log_va[12:]) #事件

    time.sleep(2)

cursor.close()
db.close()




